<template>
  <div v-if="question1.visible">
    <h3>{{ question1.text }}</h3>
    <!-- 循环遍历每一层级 -->
    <div v-for="(levelOptions, levelIndex) in getLevels()" :key="levelIndex" style="margin-bottom: 16px;">
      <!-- 使用 question.levelLabels 渲染当前层级的名称 -->
      <span>{{ question1.levelLabels[levelIndex] || `第 ${levelIndex + 1} 层` }}</span>
      <a-select
          v-model:value="answer1['answer'][levelIndex]"
          placeholder="请选择"
          style="width: 300px;"
          @change="onSelectChange(levelIndex)"
      >
        <a-select-option
            v-for="(option, optionIndex) in levelOptions"
            :key="option.value"
            :value="option.value"
        >
          {{ option.label }}
        </a-select-option>
      </a-select>
    </div>
  </div>
</template>

<script setup>
import { defineProps} from 'vue';
import {useQuestions} from "@/utils/paper.js";
const { getQuestionById,getAnswerById} = useQuestions()
// 使用 defineProps 接收父组件传递的属性
const props = defineProps({
  questionId:{
    type:String
  }
});

const questionId=props.questionId;
const question1=getQuestionById(questionId);
const answer1=getAnswerById(questionId);


// 获取每一层的选项
const getLevels = () => {
  let currentLevel = question1.options;
  const levels = [];

  for (let i = 0; i < answer1['answer'].length + 1; i++) {
    levels.push(currentLevel);
    // 获取当前选中的值
    const selected = answer1['answer'][i];
    // 找到选中的项，并获取其子项
    const nextLevel = currentLevel.find(option => option.value === selected);
    if (nextLevel && nextLevel.children) {
      currentLevel = nextLevel.children;
    } else {
      break;
    }
  }
  return levels;
};

// 当用户选择每一层的下拉框时触发
const onSelectChange = (levelIndex) => (value) => {
  // 更新选中值
  answer1['answer'].splice(levelIndex, 1, value);
  // 清空后续层级的选择
  answer1['answer'].splice(levelIndex + 1);
};
</script>

<style scoped>
</style>
